<template>
  <n-scrollbar x-scrollable style="max-height: 100vh">
    <CommonPage show-footer>
      <div>
          <n-form ref="form"
              :model="searchCondition"
              label-placement="left"
              label-align="right"
              label-width="80px"
              :show-require-mark="false">
              <div>
                <div class="grid md:flex md:flex-wrap md:gap-x-1">
                  <n-form-item>
                    <label style="width: 70px;">订单编号：</label>
                    <n-input style="width: 150px;" v-model:value="searchCondition.orderId" placeholder="输入订单编号" clearable/>
                </n-form-item>
                  <n-form-item style="margin-left: 10px">
                    <label>订单类型：</label>
                    <n-select v-model:value="searchCondition.orderType"
                              :options="orderTypes"
                              @update:value="handleOrderTypeChanged"
                    />
                </n-form-item>
                  <n-form-item style="margin-left: 10px">
                    <label>负责人：</label>
                    <n-select v-model:value="searchCondition.adminId"
                              :options="admins"
                    />
                </n-form-item>
                  <n-form-item>
                    <n-button type="primary" style="margin-left: 10px"@click="searchByCondition">筛选</n-button>
                </n-form-item>
                  <n-form-item>
                    <n-button type="primary" style="margin-left: 10px" @click="showForm=true">添加出款单</n-button>
                </n-form-item>
                  <n-form-item>
                    <n-button type="error" style="margin-left: 10px" @click="deleteSelectOutFinanceReceipts">批量删除</n-button>
                </n-form-item>
                  <n-form-item style="margin-left: 10px">
                <n-button @click="exportListInfo"
                          type="primary">
                  导出
                </n-button>
              </n-form-item>
                </div>
              </div>
            </n-form>
        <AddOutDocument :option="option" @update-page="searchByCondition" :show="showForm" :onClose="handleClose" />
        <UpdateOutDocument
            @update-page="searchByCondition"
            :show1="showForm1"
            :onClose="handleClose"
            :financeReceipt="currentFinanceReceipt"
        />
        <n-data-table
                    remote
                    :single-line="false"
                    ref="table"
                    :columns="columns"
                    :data="financeInList"
                    :loading="loading"
                    :pagination="paginationReactive"
                    :row-key="rowKey"
                    @update:checked-row-keys="handleCheck"
            />
      </div>
    </CommonPage>
  </n-scrollbar>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import api from '@/api/admin';
import {useUserStore} from '@/store';
import {useRouter} from 'vue-router';
import {formatDate} from "@/utils";
import {List} from "echarts";
import FinanceActions from "@/views/admin/category/components/category-actions.vue"
import AddOutDocument from './component/out-add.vue'
import UpdateOutDocument from './component/out-edit.vue'

const userStore = useUserStore()
const router = useRouter()
const loading = ref(true)
const range = ref(null)
const financeInList = ref([])
const searchCondition=ref({
	orderId: '',
	orderType: "全部",
	adminId:'-1',
	type: "out"
})
const showForm = ref(false)
const showForm1 = ref(false)
const handleClose = () => {
  showForm.value = false;
  showForm1.value=false;
};
const checkedRowKeysRef = ref([]);
const handleCheck = (rowKeys) => {
	checkedRowKeysRef.value = rowKeys;
}
const orderTypes = [
	{
		label: "全部",
		value: "全部"
	},
	{
		label: "客户订单",
		value: "customer_order",
	},
	{
		label: "采购订单",
		value: "purchase_order"
	},
	{
		label: "物流订单",
		value: "provider_logistics_order"
	}
]
const admins = ref([
	{
		label: '全部',
		value: "-1",
	}
])
const columns = [
	{
		type: 'selection',
		fixed: 'left',
	},
  {
    key: 'colId',
    title: '序号',
    width: 60,
  },
	{
		key: 'id',
		title: '单据编号',
		width: 100,
	},
	{
		key: 'orderId',
		title: '订单编号',
		width: 100,
	},
	{
		key: 'orderType',
		title: '订单类型',
		width: 80,
		render(row) {
			const foundOrderType = orderTypes.find(type => type.value === row.orderType);
			return foundOrderType ? foundOrderType.label : row.orderType || '';
		}
	},
	{
		key: 'price',
		title: '金额',
		width: 80,
	},
	{
		key: 'adminName',
		title: '负责人',
		width: 100,
	},
	{
		key: 'createTime',
		title: '创建时间',
		width: 100,

	},
	{
		key: 'endTime',
		title: '完成时间',
		width: 100,
	},
	{
		key: 'admin',
		title: '操作',
		width: 120,
		render(row) {
			return h(
				FinanceActions,
				{
					onClickEdit: () => onDetailOutFinanceReceipt(row),
					onClickDelete: () => onDeleteOutFinanceReceipt(row),
				}
			);
		}
	},
]
let total = 0
const paginationReactive = reactive({
	page: 1,
	pageSize: 20,
	showSizePicker: true,
	pageSizes: [20, 50, 100],
	itemCount:0,
	prefix: () => {
		return '查询出 ' + total + '条记录';
	},
	onChange: (page) => {
		paginationReactive.page = page;
		queryByPage()
	},
	onUpdatePageSize: (pageSize) => {
		paginationReactive.pageSize = pageSize;
		paginationReactive.page = 1;
		queryByPage()
	}
});
const searchByCondition = async ()=>{
	loading.value = true
	try {
		paginationReactive.page = 1;
		const res = await api.findPageFinance({
			params: {
				...searchCondition.value,
				pageNum:paginationReactive.page,
				pageSize:paginationReactive.pageSize,
			}
		})
		if(res.code === 200) {
			total = res.data.total
			paginationReactive.itemCount = total
			const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
			financeInList.value = res.data.records.map((item,i)=>{
				return {...item,
					colId: baseCount + i + 1,
				}
			})
		}
		else {
			$message.error(res.message)
		}
	} catch (err) {
		$message.error("查询出款单失败！")
	}finally{
		loading.value = false
	}
}
const onDeleteOutFinanceReceipt = async (financeReceipt)=>{
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前入款单？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const {id} = financeReceipt
      loading.value = true
      try {
        const res = await api.deleteFinanceReceipt({id})
        if(res.code === 200) {
          $message.success("删除入款单成功！")
          // await queryByPage()
          await searchByCondition()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除入款单失败！")
      }finally{
        loading.value = false
      }
    }
  })
}
const deleteSelectOutFinanceReceipts = () => {
  if(checkedRowKeysRef.value.length <= 0) {
    $message.error("当前并未选择入款单！")
    return
  }
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前所选入款单吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const ids = checkedRowKeysRef.value.join(",")
      loading.value = true
      try {
        const res = await api.deleteFinanceReceipts({params:{ids}})
        if(res.code === 200) {
          $message.success("删除所选品牌成功！")
          await searchByCondition()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除所选品牌失败！")
      }finally{
        loading.value = false
      }
    },
  })
}
const exportListInfo = async () => {
  const res = await api.exportFinanceReceiptList({
    orderId: searchCondition.value.orderId,
    orderType: searchCondition.value.orderType,
    adminId:searchCondition.value.adminId,
    type: searchCondition.value.type,
  });
  const contentDisposition = res.headers["content-disposition"]
  let original_fileName = ""
  if(contentDisposition) {
    const uri = res.headers["content-disposition"].split("=")[1]
    original_fileName = window.decodeURI(uri)
  }
  const blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
  if(window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, original_fileName);
  } else{
    const fileName = original_fileName;
    const elink = document.createElement('a')
    document.body.appendChild(elink)
    elink.download= fileName;
    elink.style.display ="none"
    elink.href  = window.URL.createObjectURL(blob)
    elink.click()
    window.URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  }
}
const currentFinanceReceipt = ref(null);
const onDetailOutFinanceReceipt = async (financeReceipt)=>{
  const {id} = financeReceipt;
  showForm1.value=true;
  currentFinanceReceipt.value = financeReceipt;
}
const queryAdminList = async () => {
	loading.value = true
	try {
		admins.value = [{
			label: "全部",
			value: "-1"
		}]
		const res = await api.findAdminByRole({
			role: 'FINANCEADMIN'
		})
		if(res.code === 200) {
			res.data.map((item)=>{
				admins.value.push({
					label: item.name,
					value: item.id
				})
			})
		}
		else {
			$message.error(res.message)
		}
	} catch (err) {
		$message.error("获取管理员信息失败！")
	}finally{
		loading.value = false
	}
}
const queryByPage = async ()=>{
	loading.value = true
	try {
		const res = await api.findPageFinance(
			{
				params: {
					type: searchCondition.value.type,
					pageNum:paginationReactive.page,
					pageSize:paginationReactive.pageSize,
				}
			})
		if(res.code === 200) {
			total = res.data.total
			paginationReactive.itemCount = total
			const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
			financeInList.value = res.data.records.map((item,i)=>{
				return {...item,
					colId: baseCount + i + 1,
				}
			})
			$message.success("获取出款单成功！")
		}
		else {
			$message.error(res.message)
		}
	} catch (err) {
		$message.error("获取出款单失败！")
	}finally{
		loading.value = false
	}
}
const rowKey = (rowData) => {
	return rowData.id
}
onMounted(()=>{
	queryAdminList("全部")
	queryByPage()
})
</script>
<style scoped>
:deep(.n-data-table-th__title),
:deep(.n-data-table-td) {
    text-align: center;

}
:deep(.n-select) {
    width: 140px !important;
}

:deep(.two-line-description) {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2; /* 控制显示的行数 */
    overflow: hidden;
}
</style>